﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using GameOn.Web.Models;

namespace GameOn.Web
{
    /// <summary>
    /// An implementation of <see cref="IView"/> for rendering <see cref="PlayerMatchesSummary"/> data as CSV
    /// </summary>
    public class PlayerCsvView : IView
    {
        private string FileName { get; set; }

        /// <summary>
        /// Instantiates a new <see cref="PlayerCsvView"/>
        /// </summary>
        /// <param name="fileName">The filename (including the csv extension) that the browser will prompt to save the CSV file as by default, e.g. players.csv</param>
        public PlayerCsvView(string fileName)
        {
            FileName = fileName;
        }

        /// <summary>
        /// Renders the specified view context by using the specified the writer object.
        /// </summary>
        /// <param name="viewContext">The view context.</param>
        /// <param name="writer">The writer object.</param>
        public void Render(ViewContext viewContext, TextWriter writer)
        {
            var summaries = viewContext.ViewData.Model as List<PlayerMatchesSummary>;
            if (summaries == null) throw new InvalidOperationException(string.Format("ViewData.Model must be of type {0}", typeof (List<PlayerMatchesSummary>).FullName));

            viewContext.HttpContext.Response.ContentType = "text/csv";
            viewContext.HttpContext.Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", FileName)); 

            writer.WriteLine("Name,Fullname,Played,Won,Lost,Current Ranking,Highest Ranking,Lowest Ranking");

            foreach (var summary in summaries)
            {
                writer.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7}", summary.Player.Name, summary.Player.Fullname, summary.Played, summary.Won, summary.Lost,
                                 summary.Player.CurrentRank, summary.HighestRanking, summary.LowestRanking);
            }
        }
    }
}